#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File    :   blk_alarm.py
@Time    :   2023-08-18 09:12:13
@Author  :   Li Rui
@Version :   1.0
@Contact :   marjey_lee@163.com
@Desc    :   None
"""
import json
import time

import requests

import ll


def _get_current_time():
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())


class BLKAlert:
    def __init__(self) -> None:
        self.internal_url = "http://blk-paas.fdb.com:80/o/cw_uac_saas/alarm/collect/event/api/8d201609-b029-4fc7-82ce-6d69ae927c14/"
        self.external_url = "http://weit.fudian-bank.com:80/o/cw_uac_saas/alarm/collect/event/api/8d201609-b029-4fc7-82ce-6d69ae927c14/"
        self.x_secret = "DclhVpHaNGtei0Yl9qBGEZP5KrpOCth9"

    @staticmethod
    def _get_alarm_template():
        return {
            "ip": "10.0.0.1",
            "source_time": _get_current_time(),
            "alarm_type": "api_default",
            "level": "remind",
            "alarm_name": "网络测试nam1e网络测试nam1e网络测试nam1e网络测试nam1e",
            "alarm_content": "网络运维conten2t网络运维conten2t",
            "meta_info": "网络告警",
            "action": "resolved",
            "bk_obj_id": "host",
            "bk_inst_id": 2,
            "bk_biz_id": 5,
        }

    def _format_alarm_content(
            self,
            ip,
            level,
            alarm_name,
            alarm_content,
            action,
    ):
        """_summary_

        Args:
            ip (_type_): _description_
            level (_type_): _description_
            alarm_name (_type_): _description_
            alarm_content (_type_): _description_
            action (_type_): _description_

        Returns:
            _type_: _description_
        """
        if level not in ["remind", "warning", "fatal"]:
            return None
        assert action in ["firing", "resolved"]
        alarm_template = self._get_alarm_template()
        alarm_template["ip"] = ip
        alarm_template["level"] = level
        alarm_template["alarm_name"] = alarm_name
        alarm_template["alarm_content"] = alarm_content
        alarm_template["action"] = action
        return alarm_template

    def _post_info(self, url, data):
        """post request

        Args:
            url (_type_): _description_
            data (_type_): _description_
        """
        try:
            headers = {
                "X-Secret": self.x_secret,
                "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/" +
                              "537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat",
                "Accept-Encoding": "gzip, deflate",
                "Accept": "application/json, text/javascript, */*; q=0.01",
                "Connection": "keep-alive",
                "Content-Type": "application/json",
            }
            # data = json.dumps(data)
            res = requests.post(url, json=data, headers=headers)
            res = json.loads(res.text)
            return res
        except Exception as e:
            ll.get_logger().error(e)
            return {
                "result": False,
            }

    def send_external_alarm(
            self,
            ip,  # 每次发出告警的机器ip 不能相同，相同会被抑制。
            level,
            alarm_name,
            alarm_content,
            action,
    ):
        """send external alarm

        Args:
            ip (_type_): _description_
            level (_type_): _description_
            alarm_name (_type_): _description_
            alarm_content (_type_): _description_
            action (_type_): _description_
        """
        return self.send_alarm(  # pylint: disable=unexpected-keyword-arg
            ip=ip,
            level=level,
            alarm_name=alarm_name,
            alarm_content=alarm_content,
            action=action,
            url=self.external_url,
        )

    def send_alarm(
            self,
            ip,  # 每次发出告警的机器ip 不能相同，相同会被抑制。
            level,
            alarm_name,
            alarm_content,
            action,
            url,
    ):
        """send external alarm

        Args:
            url:
            ip (_type_): _description_
            level (_type_): _description_
            alarm_name (_type_): _description_
            alarm_content (_type_): _description_
            action (_type_): _description_
        """
        content = self._format_alarm_content(
            ip=ip,
            level=level,
            alarm_name=alarm_name,
            alarm_content=alarm_content,
            action=action,
        )
        if content is None:
            ll.get_logger().warning('Alarm content is None')
            return None
        if action == 'resolved':
            ll.get_logger().info(f"send resolved info: \n{content} ")
        else:
            ll.get_logger().warning(f"send alarm: \n{content} ")
        res = self._post_info(url=url, data=content)
        if not res["result"]:
            ll.get_logger().error(f"send alarm error: \n{content} ")
        return res

    def send_internal_alarm(
            self,
            ip,  # 每次发出告警的机器ip 不能相同，相同会被抑制。
            level,
            alarm_name,
            alarm_content,
            action,
    ):
        """send external alarm

        Args:
            ip (_type_): _description_
            level (_type_): _description_
            alarm_name (_type_): _description_
            alarm_content (_type_): _description_
            action (_type_): _description_
        """

        return self.send_alarm(
            ip=ip,
            level=level,
            alarm_name=alarm_name,
            alarm_content=alarm_content,
            action=action,
            url=self.internal_url,
        )
